package com.hongyuan.sellfitness.ui.home.view_mode;

import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.hongyuan.mvvmhabitx.binding.command.BindingAction;
import com.hongyuan.mvvmhabitx.binding.command.BindingCommand;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.mvvmhabitx.utils.ToastUtils;
import com.hongyuan.sellfitness.BR;
import com.hongyuan.sellfitness.R;
import com.hongyuan.sellfitness.base.Constants;
import com.hongyuan.sellfitness.base.CustomViewModel;
import com.hongyuan.sellfitness.data.MyRepository;
import com.hongyuan.sellfitness.data.md5.BaseUtil;
import com.hongyuan.sellfitness.my_view.scllor_view.UnitBeanUtils;
import com.hongyuan.sellfitness.ui.home.activity.UseCouponListActivity;
import com.hongyuan.sellfitness.ui.home.beans.BuyOrderBean;
import com.hongyuan.sellfitness.ui.home.beans.CardDetailsBean;
import com.hongyuan.sellfitness.ui.home.beans.CouponBean;
import com.hongyuan.sellfitness.ui.home.beans.SalerBean;
import com.hongyuan.sellfitness.ui.main.activity.PayActivity;
import com.hongyuan.sellfitness.ui.main.activity.SuccessActivity;
import com.hongyuan.sellfitness.ui.main.beans.V3SuccessBeans;
import com.hongyuan.sellfitness.ui.person.beans.MInfoBean;
import com.hongyuan.sellfitness.utils.BigDecimalUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class BuyCardViewModel extends CustomViewModel<MyRepository> {

    //配送方式选择工具类
    public UnitBeanUtils rUtils;
    //销售顾问
    public String salerName;

    private Disposable mSubscription;

    public ObservableField<CardDetailsBean> entity = new ObservableField<>();

    public ObservableField<MInfoBean> info = new ObservableField<>();

    public ObservableField<CouponBean.ListBean> couponBean = new ObservableField<>();

    public ObservableField<String> allPrice = new ObservableField<>();

    public BuyCardViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //显示滚动弹框
        public SingleLiveEvent<Void> showSaler = new SingleLiveEvent<>();
        //选择性别
        public SingleLiveEvent<Void> selectSex = new SingleLiveEvent<>();
        //选择生日
        public SingleLiveEvent<Void> selectBirth = new SingleLiveEvent<>();
        //通知显示优惠卷信息
        public SingleLiveEvent<String> showCouponName = new SingleLiveEvent<>();
        //显示销售顾问初始值
        public SingleLiveEvent<List<SalerBean.ListBean>> setSalers = new SingleLiveEvent<>();
    }

    //给RecyclerView添加ObservableList
    public ObservableList<BuyLessonItmeViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<BuyLessonItmeViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_buy_lesson);



    //生成私订单
    public BindingCommand goPay = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(!BaseUtil.isValue(info.get().getMi_realname())){
                ToastUtils.showShort("请输入真实姓名！");
                return;
            }
            if(!BaseUtil.isValue(info.get().getMi_birth())){
                ToastUtils.showShort("请选择生日！");
                return;
            }

            //会员--读取会员基本信息
            clearParams().setParams("mi_birth",info.get().getMi_birth()).setParams("mi_realname",info.get().getMi_realname())
                    .setParams("mi_sex",String.valueOf(info.get().getMi_sex()));
            requestData(Constants.UPDATE_M_INFO);
        }
    });
    //选择销售顾问
    public BindingCommand selectSaler = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.showSaler.call();
        }
    });
    //选择性别
    public BindingCommand selectSex = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.selectSex.call();
        }
    });
    //选择生日
    public BindingCommand selectBirth = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.selectBirth.call();
        }
    });
    //选取优惠券
    public BindingCommand selectCoupon = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putString("couponFor","2");
            bundle.putString("totalMoney",allPrice.get());
            //bundle.putInt("couponId",couponId);
            bundle.putString("os_id",userToken.getOs_id());
            startActivity(UseCouponListActivity.class,bundle);
        }
    });


    @Override
    public void onCreate() {
        super.onCreate();

        mSubscription = RxBus.getDefault().toObservable(CouponBean.ListBean.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(coupon -> {
                    if(coupon != null && BaseUtil.isValue(coupon.getCoupon_money())){
                        uc.showCouponName.setValue(coupon.getCoupon_name());

                        if(couponBean.get() == null || !BaseUtil.isValue(couponBean.get().getCoupon_money())){
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.sub(allPrice.get(),coupon.getCoupon_money(),2)));
                        }else{
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.add(allPrice.get(),couponBean.get().getCoupon_money(),2)));
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.sub(allPrice.get(),coupon.getCoupon_money(),2)));
                        }
                        couponBean.set(coupon);

                    }else{
                        if(couponBean.get() != null && BaseUtil.isValue(couponBean.get().getCoupon_money())){
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.add(allPrice.get(),couponBean.get().getCoupon_money(),2)));
                        }

                        uc.showCouponName.setValue("");
                        couponBean.set(null);
                    }

                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_CARD_INFO){
            CardDetailsBean bean = (CardDetailsBean)dataBean;
            entity.set(bean);
            allPrice.set(bean.getCard_sale_price());

            //读取销售顾问
            setParams("os_id",userToken.getOs_id());
            requestData(Constants.GET_SALER_LIST);
        }

        if(code == Constants.GET_M_INFO){
            MInfoBean bean = (MInfoBean)dataBean;
            info.set(bean);
        }

        if(code == Constants.GET_SALER_LIST){
            List<SalerBean.ListBean> mList = ((SalerBean)dataBean).getList();

            uc.setSalers.setValue(mList);

            rUtils = new UnitBeanUtils<SalerBean.ListBean>() {
                @Override
                public String unit(SalerBean.ListBean o) {
                    return String.valueOf(o.getM_id());
                }

                @Override
                public String unit_cn(SalerBean.ListBean o) {
                    return o.getMi_realname();
                }
            };
        }

        if(code == Constants.UPDATE_M_INFO){
            clearParams().setParams("card_id",String.valueOf(entity.get().getCard_id()))
                    .setParams("oc_num","1");
            if(couponBean.get() != null && BaseUtil.isValue(couponBean.get().getCm_id())){
                setParams("cm_id",String.valueOf(couponBean.get().getCm_id()));
            }
            if(BaseUtil.isValue(salerName)){
                setParams("saler_id",rUtils.getMessage(salerName));
            }

            requestData(Constants.ADD_CARD_ORDER);
        }


        if(code == Constants.ADD_CARD_ORDER){
            BuyOrderBean orderBean = (BuyOrderBean)dataBean;
            if(Double.valueOf(entity.get().getCard_sale_price()) <= 0){
                V3SuccessBeans beans = new V3SuccessBeans();
                beans.setType(V3SuccessBeans.TYPE.BUYGOODS);
                beans.setTitleText("领取结果");
                beans.setShowText("领取成功");
                beans.setBtn2Text("返回");

                Bundle bundle = new Bundle();
                bundle.putSerializable("successBeans",beans);
                startActivity(SuccessActivity.class,bundle);
                finish();
            }else{
                V3SuccessBeans beans = new V3SuccessBeans();
                beans.setType(V3SuccessBeans.TYPE.BUYCARD);
                beans.setTitleText("订单完成");
                beans.setShowText("购买成功");
                //beans.setBtn1Text("跳过");
                //beans.setBtn2Text("人脸识别录入");
                //beans.setBtn1Text("跳过");
                beans.setBtn2Text("完成");
                List<V3SuccessBeans.ItemConten> list = new ArrayList<>();

                V3SuccessBeans.ItemConten itemConten = new V3SuccessBeans.ItemConten();
                itemConten.setContent(entity.get().getCard_name()+"");
                itemConten.setItemTitle("会籍卡名称:");
                list.add(itemConten);

                itemConten = new V3SuccessBeans.ItemConten();
                itemConten.setContent(entity.get().getOs_name());
                itemConten.setItemTitle("门店:");
                list.add(itemConten);

                itemConten = new V3SuccessBeans.ItemConten();
                itemConten.setContent("￥"+entity.get().getCard_sale_price());
                itemConten.setItemTitle("价格:");
                list.add(itemConten);

                if(couponBean.get() != null){
                    itemConten = new V3SuccessBeans.ItemConten();
                    itemConten.setContent("-¥"+BaseUtil.getNoZoon(couponBean.get().getCoupon_money()));
                    itemConten.setItemTitle("优惠:");
                    list.add(itemConten);
                }
                beans.setItemContens(list);

                Bundle bundle = new Bundle();
                bundle.putString("payPrice",allPrice.get());
                bundle.putString("payOid",orderBean.getO_id());
                bundle.putSerializable("successBeans",beans);
                startActivity(PayActivity.class,bundle);
            }

            finish();
        }
    }
}
